package com.example.myapplication.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Token管理工具类
 * 用于存储和管理用户登录token
 */
public class TokenManager {
    
    private static final String PREF_NAME = "greenhouse_prefs";
    private static final String KEY_TOKEN = "access_token";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    
    public TokenManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    
    /**
     * 保存登录信息
     * @param token 访问token
     * @param refreshToken 刷新token
     * @param username 用户名
     */
    public void saveLoginInfo(String token, String refreshToken, String username) {
        editor.putString(KEY_TOKEN, token);
        editor.putString(KEY_REFRESH_TOKEN, refreshToken);
        editor.putString(KEY_USERNAME, username);
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.apply();
    }
    
    /**
     * 获取访问token
     * @return 访问token
     */
    public String getToken() {
        return sharedPreferences.getString(KEY_TOKEN, null);
    }
    
    /**
     * 获取刷新token
     * @return 刷新token
     */
    public String getRefreshToken() {
        return sharedPreferences.getString(KEY_REFRESH_TOKEN, null);
    }
    
    /**
     * 获取用户名
     * @return 用户名
     */
    public String getUsername() {
        return sharedPreferences.getString(KEY_USERNAME, null);
    }
    
    /**
     * 检查是否已登录
     * @return 是否已登录
     */
    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }
    
    /**
     * 清除登录信息（退出登录）
     */
    public void clearLoginInfo() {
        editor.clear();
        editor.apply();
    }
    
    /**
     * 更新访问token
     * @param token 新的访问token
     */
    public void updateToken(String token) {
        editor.putString(KEY_TOKEN, token);
        editor.apply();
    }
}
